package com.party.course.service.impl;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.hutool.core.date.DateUtil;
import com.party.business.domain.KcType;
import com.party.business.mapper.KcTypeMapper;
import com.party.common.core.domain.entity.SysRole;
import com.party.common.core.domain.entity.SysUser;
import com.party.common.utils.CodeNoUtils;
import com.party.common.utils.SecurityUtils;
import com.party.course.domain.*;
import com.party.course.mapper.*;
import com.party.course.service.ICoachTimeService;
import com.party.course.service.INoticeInfoService;
import com.party.system.mapper.SysRoleMapper;
import com.party.system.mapper.SysUserMapper;
import com.party.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import com.party.course.service.ICoachInfoService;

import cn.hutool.core.util.IdUtil;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 教练Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-29
 */
@Service
public class CoachInfoServiceImpl extends ServiceImpl<CoachInfoMapper, CoachInfo> implements ICoachInfoService {
    @Resource
    private CoachInfoMapper coachInfoMapper;
    @Resource
    private ISysUserService userService;
    @Resource
    private StudentInfoMapper studentInfoMapper;
    @Resource
    private PlanClassMapper planClassMapper;
    @Resource
    private CoachLevelInfoMapper coachLevelInfoMapper;
    @Resource
    private PayGroupMapper payGroupMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private ICoachTimeService coachTimeService;
    @Resource
    private KcTypeMapper kcTypeMapper;
    @Resource
    private AmountInfoMapper amountInfoMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private INoticeInfoService noticeInfoService;

    /**
     * 定时任务，每天下午6点发送通知提醒 学管有多少条反馈未发
     */
    @Override
    @Transactional
    public void taskFind() {
        try {
            //查询所有学管师
            List<CoachInfo> learnCoach = coachInfoMapper.selectCoachInfoList(CoachInfo.builder().roleType("2").build());
            if (!learnCoach.isEmpty()){
                for (CoachInfo coach : learnCoach) {
                    //查询当天学管下的所有课程
                    List<PlanClass> classList = planClassMapper.selectplanClassList(PlanClass.builder().leaId(coach.getId()).classTime(DateUtil.today()).build());
                    //课后反馈未发-计数
                    int feedBackNum = 0;
                    if (!classList.isEmpty()){
                        for (PlanClass planClass : classList) {
                            if (StrUtil.isEmpty(planClass.getLearnRemark())){
                                feedBackNum ++;
                            }
                        }
                    }
                    if(StrUtil.isNotEmpty(coach.getUserId())){
                        //发送消息通知给学管
                        noticeInfoService.add(NoticeInfo.builder()
                                .userId(coach.getUserId())
                                .userName(coach.getName())
                                .notice(feedBackNum+"条课后反馈未发")
                                .build());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询教练
     *
     * @param id 教练主键
     * @return 教练
     */
    @Override
    public CoachInfo view(String id) {
        CoachInfo coachInfo = coachInfoMapper.selectCoachInfoById(id);
        List<CoachTime> coachTimes = coachTimeService.findByCoachId(id);
        coachInfo.setCoachTimes(coachTimes);
        return coachInfo;
    }

    /**
     * 查询教练列表
     *
     * @param coachInfo 教练
     * @return 教练
     */
    @Override
    public List<CoachInfo> findList(CoachInfo coachInfo) {
        coachInfo.setCreateBy(SecurityUtils.getDataPower());
        // 根据教练信息查询教练列表
        List<CoachInfo> coachInfos = coachInfoMapper.selectCoachInfoList(coachInfo);
        // 遍历教练列表
        for (CoachInfo info : coachInfos) {
//            // 根据教练id查询教练等级信息
//            CoachLevelInfo coachLevelInfo = coachLevelInfoMapper.findByCoachId(info.getId());
//            // 如果教练等级信息不为空，则设置教练等级名称
//            if (coachLevelInfo != null) {
//                info.setLevelName(coachLevelInfo.getName());
//            } else {
//                // 否则设置教练等级名称为"无"
//                info.setLevelName("无");
//            }
            // 根据创建人id查询用户信息-交付中心
            SysUser user = userService.selectUserById(Long.parseLong(info.getCreateBy()));
            // 设置用户编码和用户名称
            info.setPaCenterCode(user.getCode());
            info.setPaCenterName(user.getUserName());
            //试课
            List<PlanClass> list1 = planClassMapper.findByCoachId(info.getId(), "0");
            //正式课
            List<PlanClass> list2 = planClassMapper.findByCoachId(info.getId(), "1");
            //试课+正式课
            List<PlanClass> list3 = planClassMapper.findByCoachId(info.getId(), "2");
            int i1 = list1.size() + list3.size();
            info.setAgentCourse(i1 + "");
            int i2 = list2.size() + list3.size();
            info.setFormalCourse(i2 + "");
            //判断交付小组组长是否绑定交付小组
            List<PayGroup> groups = payGroupMapper.findByGroupUser(info.getId());
            if (groups.size() > 0) {
                info.setIsPayGroup("0");
            } else {
                info.setIsPayGroup("1");
            }
        }
        return coachInfos;
    }

    @Override
    public List<CoachInfo> findAll(CoachInfo coachInfo) {
        if (StrUtil.isNotEmpty(coachInfo.getIsNotGroup())&&"0".equals(coachInfo.getIsNotGroup())){
            //查询未分组的教练
            List<CoachInfo> coachInfos = coachInfoMapper.findNotGroup(SecurityUtils.getDataPower());
            coachInfo.setMemberIdsList(coachInfos);
        }
        coachInfo.setCreateBy(SecurityUtils.getDataPower());
        List<CoachInfo> coachInfos = coachInfoMapper.selectCoachInfoList(coachInfo);

        return  coachInfos;
    }

    @Override
    public List<CoachInfo> findCoachAmount(CoachInfo coachInfo) {
        String username = SecurityUtils.getUsername();
        List<CoachInfo> amounts=new ArrayList<>();
        if("admin".equals(username)){
            amounts=amountInfoMapper.findByUserAll();
        }else{
            amounts=amountInfoMapper.findByUserId(SecurityUtils.getUserIdStr());
        }
        if(!amounts.isEmpty()){
            for (CoachInfo amount : amounts) {
                if(StrUtil.isNotEmpty(amount.getCreateBy())){
                    // 根据创建人id查询用户信息-交付中心
                    SysUser user = userService.selectUserById(Long.parseLong(amount.getCreateBy()));
                    // 设置用户编码和用户名称
                    amount.setPaCenterCode(user.getCode());
                    amount.setPaCenterName(user.getUserName());
                }
            }
        }
        return amounts;
    }

    /**
     * 新增教练
     *
     * @param coachInfo 教练
     * @return 结果
     */
    @Override
    @Transactional
    public int add(CoachInfo coachInfo) {
        // 生成教练ID
        coachInfo.setId(IdUtil.simpleUUID());
        // 设置删除标志为0
        coachInfo.setDelFlag("0");
        addOthers(coachInfo);
        addUserByCoach(coachInfo);
        // 添加教练信息
        return coachInfoMapper.insert(coachInfo);
    }

    /**
     * 根据教练信息添加新用户
     * @param coachInfo
     */
    @Transactional
    public void addUserByCoach(CoachInfo coachInfo){
        if (StrUtil.isNotEmpty(coachInfo.getPhone())){
            SysUser user = sysUserMapper.findByPhone(coachInfo.getPhone());
            if (ObjectUtil.isNotEmpty(user) && !user.getUserId().toString().equals(coachInfo.getUserId())){
                throw new RuntimeException("该手机号已存在，请重新输入");
            }
        }
        //新增用户
        SysUser user = sysUserMapper.selectUserByUserName(coachInfo.getName());
        if (ObjectUtil.isEmpty(user)){
            if (StrUtil.isNotEmpty(coachInfo.getPhone())){
                user = sysUserMapper.findByPhone(coachInfo.getPhone());
            }
            if (ObjectUtil.isEmpty(user)) {
                user = new SysUser();
            }
        }
        user.setUserName(coachInfo.getName());
        user.setNickName(coachInfo.getName());
        user.setPhonenumber(coachInfo.getPhone());
        user.setSex(coachInfo.getSex());
        if (StrUtil.isNotEmpty(coachInfo.getRoleType())){
            Long roleId;
            if ("1".equals(coachInfo.getRoleType())){
                SysRole role = sysRoleMapper.findByRoleName("交付小组组长");
                roleId = role.getRoleId();
            }else if ("2".equals(coachInfo.getRoleType())){
                SysRole role = sysRoleMapper.findByRoleName("学管师");
                roleId = role.getRoleId();
            }else {
                SysRole role = sysRoleMapper.findByRoleName("教练");
                roleId = role.getRoleId();
            }
            user.setRoleId(roleId);
            Long[] roleIds = new Long[1];
            roleIds[0] = roleId;
            user.setRoleIds(roleIds);
        }
        String password = SecurityUtils.encryptPassword("123456");
        user.setPassword(password);
        user.setCode(CodeNoUtils.getUserCode());
        if (user.getUserId()!= null){
            userService.updateUser(user);
        }else {
            userService.insertUser(user);
        }
        coachInfo.setUserId(user.getUserId().toString());
    }

    public void addOthers(CoachInfo coachInfo) {
        //课程分类
        if (StrUtil.isNotEmpty(coachInfo.getClassTypeId())){
            KcType kcType = kcTypeMapper.selectKcTypeById(coachInfo.getClassTypeId());
            if (ObjectUtil.isNotEmpty(kcType)) {
                coachInfo.setClassTypeName(kcType.getName());
            }
        }
        // 如果学管师ID不为空
        if (StrUtil.isNotEmpty(coachInfo.getLearnId())) {
            // 根据学管师ID查询支付组信息
            CoachInfo info = coachInfoMapper.selectCoachInfoById(coachInfo.getLearnId());
            // 如果支付组信息不为空
            if (ObjectUtil.isNotEmpty(info)) {
                // 设置教练的学管师名称
                coachInfo.setLearnName(info.getName());
            }
        }
        // 如果教练的支付组ID不为空
        if (StrUtil.isNotEmpty(coachInfo.getPayGroupId())) {
            // 根据支付组ID查询支付组信息
            PayGroup payGroup = payGroupMapper.selectPayGroupById(coachInfo.getPayGroupId());
            // 如果支付组信息不为空
            if (ObjectUtil.isNotEmpty(payGroup)) {
                // 设置教练的支付组名称
                coachInfo.setPayGroupName(payGroup.getName());
                if (StrUtil.isNotEmpty(payGroup.getMemberIds())) {
                    payGroup.setMemberIds(payGroup.getMemberIds() + "," + coachInfo.getId()+",");
                }else {
                    payGroup.setMemberIds(coachInfo.getId()+",");
                }
                if (StrUtil.isNotEmpty(payGroup.getMemberNames())) {
                    payGroup.setMemberNames(payGroup.getMemberNames() + "," + coachInfo.getName()+",");
                }else {
                    payGroup.setMemberNames(coachInfo.getName()+",");
                }
                payGroupMapper.updateById(payGroup);
            }
        }
        // 如果教练的角色类型不为空
        if (StrUtil.isNotEmpty(coachInfo.getRoleType())) {
            // 定义角色名称
            String roleName = "教练";
            // 根据角色类型设置角色名称
            if ("0".equals(coachInfo.getRoleType())) {
                roleName = "教练";
            } else if ("1".equals(coachInfo.getRoleType())) {
                roleName = "交付小组组长";
            } else if ("2".equals(coachInfo.getRoleType())) {
                roleName = "学管师";
            }
            // 根据角色名称查询角色信息
            SysRole sysRole = sysRoleMapper.findByRoleName(roleName);
            // 设置教练的角色ID
            coachInfo.setRoleId(sysRole.getRoleId().toString());
        } else {
            // 如果角色类型为空，抛出异常
            throw new RuntimeException("请选择角色类型");
        }
        // 如果教练的教练时间不为空
        if (ObjectUtil.isNotEmpty(coachInfo.getCoachTimes()) && !coachInfo.getCoachTimes().isEmpty()) {
            coachTimeService.deleteByCoachId(coachInfo.getId());
            // 遍历教练时间
            for (CoachTime coachTime : coachInfo.getCoachTimes()) {
                // 设置教练时间对应的教练ID
                coachTime.setCoachId(coachInfo.getId());
                // 添加教练时间
                coachTimeService.add(coachTime);
            }
        }
    }

    /**
     * 修改教练
     *
     * @param coachInfo 教练
     * @return 结果
     */
    @Override
    @Transactional
    public int updateEntity(CoachInfo coachInfo) {
        try {
            if (StrUtil.isNotEmpty(coachInfo.getPhone())){
                CoachInfo coach = coachInfoMapper.findByPhone(coachInfo.getPhone());
                if (ObjectUtil.isNotEmpty(coach)&& !coachInfo.getId().equals(coach.getId())){
                    throw new RuntimeException("该手机号已存在，请重新输入");
                }
            }
            coachInfo.setIsUse("0");
            coachInfo.setUpdateTime(DateUtil.date());
            addOthers(coachInfo);
            if (StrUtil.isNotEmpty(coachInfo.getUserId())){
                addUserByCoach(coachInfo);
            }
            return coachInfoMapper.updateById(coachInfo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 批量删除教练
     *
     * @param ids 需要删除的教练主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteIds(List<String> ids) {
        return coachInfoMapper.deleteCoachInfoByIds(ids);
    }

    /**
     * 删除教练信息
     *
     * @param id 教练主键
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        return coachInfoMapper.deleteCoachInfoById(id);
    }

    @Override
    public CoachInfo findByPhone(String phone) {
        return coachInfoMapper.findByPhone(phone);
    }
}
